package com.itheima.ssm.controller;

import com.itheima.ssm.domain.Pemission;
import com.itheima.ssm.domain.Role;
import com.itheima.ssm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService iRoleService;

    @RequestMapping("/findAll.do")
    public ModelAndView findAll() throws Exception{
        ModelAndView mv = new ModelAndView();
        List<Role> roleList = iRoleService.findAll();
        mv.addObject("roleList",roleList);
        mv.setViewName("role-list");
        return mv;
    }

    /**
     * 添加角色
     * @return
     */
    @RequestMapping("/save.do")
    public String save(Role role) throws Exception{
        iRoleService.save(role);
        return "redirect:findAll.do";
    }

    @RequestMapping("/deleteRole.do")
    public String deletRole(@RequestParam(name = "roleId",required = false) int roleId) throws Exception {
        iRoleService.deleteRoleById(roleId);
        return "redirect:findAll.do";
    }

    /**
     * 返回角色可以添加的权限到页面上
     * @param roleId
     * @return
     */
    @RequestMapping("/findRoleByIdAndAllPermission.do")
    public ModelAndView findRoleByIdAndAllPermission(@RequestParam("id") String roleId) throws Exception{
        ModelAndView mv = new ModelAndView();
        Role role = iRoleService.findById(roleId);
        List<Pemission> pemissionList = iRoleService.findOtherPermission(roleId);
        mv.addObject("role",role);
        mv.addObject("pemissionList",pemissionList);
        return mv;
    }

    @RequestMapping("/addPermissionToRole.do")
    public void addPermissionToRole(@RequestParam(name = "roleId") String roleId,@RequestParam("ids") String[] pids) throws Exception{
        iRoleService.addPermissionToRole(roleId,pids);
    }

}
